<template>
  <span class="region-select-container">
    <div class="region-select-main">
      <div v-if="level>=1" class="region-item">
        <el-select v-model="regionInfo.provinceId" filterable @change="handlerChange(1)">
          <el-option value="" :label="'请选择省'" />
          <el-option v-for="item in provinces" :key="item.id" :value="item.id" :label="item.name" />
        </el-select>
      </div>
      <div v-if="level>=2" class="region-item">
        <el-select v-model="regionInfo.cityId" filterable @change="handlerChange(2)">
          <el-option value="" :label="'请选择市'" />
          <el-option v-for="item in citys" :key="item.id" :value="item.id" :label="item.name" />
        </el-select>
      </div>
      <div v-if="level>=3" class="region-item">
        <el-select v-model="regionInfo.areaId" filterable @change="handlerChange(3)">
          <el-option value="" :label="'请选择区县'" />
          <el-option v-for="item in areas" :key="item.id" :value="item.id" :label="item.name" />
        </el-select>
      </div>
      <div v-if="level>=4" class="region-item">
        <el-select v-model="regionInfo.streetId" filterable @change="handlerChange(4)">
          <el-option value="" :label="'请选择街道'" />
          <el-option v-for="item in streets" :key="item.id" :value="item.id" :label="item.name" />
        </el-select>
      </div>
    </div>
    <div v-if="value" class="region-select-tip">
      当前选择：{{ value }}
    </div>
  </span>
</template>

<script>
export default {
  name: 'RegionSelector',
  props: {
    // v-model
    value: {
      type: Array,
      default: function() {
        return []
      }
    },
    // 级别  1：省 2：省市 3：省市区 4：省市区街道，默认4
    level: {
      type: Number,
      default: 4
    }
  },
  data() {
    return {
      regionInfo: {
        provinceId: '',
        cityId: '',
        areaId: '',
        streetId: ''
      },
      provinces: [],
      citys: [],
      areas: [],
      streets: [],
      selectedInfo: {}
    }
  },
  watch: {
    'regionInfo.provinceId': function(val) {
      if (this.level < 2) {
        return
      }
      if (val) {
        this.getCity()
      } else {
        this.citys = []
        this.regionInfo = {
          ...this.regionInfo,
          cityId: '',
          areaId: '',
          streetId: ''
        }
      }
    },
    'regionInfo.cityId': function(val) {
      if (this.level < 3) {
        return
      }
      if (val) {
        this.getArea()
      } else {
        this.areas = []
        this.regionInfo = {
          ...this.regionInfo,
          areaId: '',
          streetId: ''
        }
      }
    },
    'regionInfo.areaId': function(val) {
      if (this.level < 4) {
        return
      }
      if (val) {
        this.getStreet()
      } else {
        this.streets = []
        this.regionInfo = {
          ...this.regionInfo,
          streetId: ''
        }
      }
    },
    'regionInfo.streetId': function(val) {
    },
    value: function(val) {
      this.analysisRegionResult(this.value)
    }
  },
  created: function() {
    this.getProvince()
    this.analysisRegionResult(this.value)
  },
  methods: {
    // 省
    async getProvince() {
      const response = await this.$store.dispatch('getCacheRegion', 100000)
      if (response.length === 0) {
        this.$alert('当前系统还未缓存地区，单击确定进行缓存！', '提示', {
          confirmButtonText: '确定',
          showClose: false,
          callback: action => {
            this.handleSyncCacheRegion()
          }
        })
      }
      this.provinces = [...response]
    },
    // 市
    async getCity() {
      const response = await this.$store.dispatch('getCacheRegion', this.regionInfo.provinceId)
      this.citys = [...response]
    },
    // 县
    async getArea() {
      const response = await this.$store.dispatch('getCacheRegion', this.regionInfo.cityId)
      this.areas = [...response]
    },
    // 街道
    async getStreet() {
      const response = await this.$store.dispatch('getCacheRegion', this.regionInfo.areaId)
      this.streets = [...response]
      if (this.streets.length === 0) {
        this.getSelected()
      }
    },

    analysisRegionResult(val) {
      if (val.length !== 0) {
        this.regionInfo = {
          provinceId: val[0] ? val[0] : '',
          cityId: val[1] ? val[1] : '',
          areaId: val[2] ? val[2] : '',
          streetId: val[3] ? val[3] : ''
        }
      } else {
        this.regionInfo = {
          provinceId: '',
          cityId: '',
          areaId: '',
          streetId: ''
        }
      }
    },
    async handleSyncCacheRegion() {
      await this.$store.dispatch('syncCacheRegion')
      this.$modal.msgSuccess('缓存成功')
      this.getProvince()
    },

    setSelected() {

    },
    getSelected() {
      const selectedIds = []
      const selectedRegionName = []
      this.provinces.forEach(item => {
        if (item.id === this.regionInfo.provinceId) {
          selectedIds.push(item.id)
          selectedRegionName.push(item.name)
        }
      })
      this.citys.forEach(item => {
        if (item.id === this.regionInfo.cityId) {
          selectedIds.push(item.id)
          selectedRegionName.push(item.name)
        }
      })
      this.areas.forEach(item => {
        if (item.id === this.regionInfo.areaId) {
          selectedIds.push(item.id)
          selectedRegionName.push(item.name)
        }
      })
      if (this.streets.length > 0) {
        this.streets.forEach(item => {
          if (item.id === this.regionInfo.streetId) {
            selectedIds.push(item.id)
            selectedRegionName.push(item.name)
          }
        })
      } else {
        selectedIds.push(0)
        selectedRegionName.push('item.name')
      }

      this.selectedInfo = {
        regionIds: selectedIds,
        regionNames: selectedRegionName,
        regionName: selectedRegionName.join('')
      }
      this.$emit('input', this.selectedInfo.regionIds)
      this.$emit('selected', this.selectedInfo)
    },
    handlerChange(level) {
      if (level === 1) {
        if (this.level === 1) {
          this.getSelected()
          return
        }
        this.regionInfo = {
          ...this.regionInfo,
          cityId: '',
          areaId: '',
          streetId: ''
        }
      }
      if (level === 2) {
        if (this.level === 2) {
          this.getSelected()
          return
        }
        this.regionInfo = {
          ...this.regionInfo,
          areaId: '',
          streetId: ''
        }
      }
      if (level === 3) {
        if (this.level === 3) {
          this.getSelected()
          return
        }
        this.regionInfo = {
          ...this.regionInfo,
          streetId: ''
        }
      }
      if (level === 4) {
        this.getSelected()
      }
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>

 .region-select-container{
  display: flex;
  flex-direction: column;
 }
 .region-select-main{
  display: flex;
  flex-direction: row;
  .region-item{
    margin-right: 5px;
  }
 }
 .region-select-tip{
  font-size: 12px;
 }
</style>
